package com.mhc.suzuki.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mhc.suzuki.constant.SmsConstant;
import com.mhc.suzuki.constant.SmsTypeEnum;
import com.mhc.suzuki.vo.SmsTplVO;
import com.subaru.common.entity.BizResult;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.ws.rs.core.MediaType;
import java.util.List;

/**
 * Created by zheng on 16/5/9.
 */
@Slf4j
public class YunPianUtil {
    /**
     * 云片发自动匹配模板短信 -- 系统短信
     *
     * @param text   短信内容
     * @param mobile 接受的手机号
     * @return json格式字符串
     * @throws Exception
     */
    public static BizResult<String> sendYunPianSmsForJson(String apiKey, String text, String mobile, String extend) {
        MultivaluedMapImpl formData = new MultivaluedMapImpl();
        formData.add("apikey", apiKey);
        formData.add("text", text);
        formData.add("mobile", mobile);
        if (!StringUtils.isEmpty(extend)) {
            formData.add("extend", extend);
        }

        ClientConfig cc = new DefaultClientConfig();
        cc.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 10 * 1000);
        Client client = Client.create(cc);

        WebResource webResource = client.resource(SmsConstant.YP_SMS_SEND_URL);
        ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class,
                formData);

        String result = response.getEntity(String.class);

        BizResult<String> bizResult = new BizResult();
        if (StringUtils.isBlank(result)) {
            bizResult.setMessage("发送短信失败");
            return bizResult;
        }

        try {
            JSONObject jsonObj = JSON.parseObject(result);
            if (null == jsonObj) {
                bizResult.setMessage("发送短信失败");
                return bizResult;
            }
            String code = jsonObj.getString("code");
            if (!"0".equals(code)) {
                log.error("发送短信失败，jsonObj" + jsonObj.toJSONString());
                bizResult.setMessage("信息发送失败");
            }
        } catch (Exception e) {
            log.error("发送短信失败" + e);
            bizResult.setMessage("信息发送失败");
        }
        return bizResult;
    }

    /**
     * 云片发自动匹配模板短信 -- 营销短信
     *
     * @param text   短信内容
     * @param mobile 接受的手机号
     * @return json格式字符串
     * @throws Exception
     */
    public static BizResult<String> sendYunPianSEMSmsForJson(String text, String mobile, String extend) {
        MultivaluedMapImpl formData = new MultivaluedMapImpl();
        formData.add("apikey", SmsConstant.YP_SMS_SEM_API_KEY);
        formData.add("text", text);
        formData.add("mobile", mobile);
        if (!StringUtils.isEmpty(extend)) {
            formData.add("extend", extend);
        }

        Client client = Client.create();

        WebResource webResource = client.resource(SmsConstant.YP_SMS_SEND_URL);
        ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class,
                formData);

        String result = response.getEntity(String.class);
        BizResult<String> bizResult = new BizResult<String>();
        if (StringUtils.isBlank(result)) {
            bizResult.setMessage("发送短信失败");
            return bizResult;
        }

        try {
            JSONObject jsonObj = JSON.parseObject(result);
            if (null == jsonObj) {
                bizResult.setMessage("发送短信失败");
                return bizResult;
            }
            String code = jsonObj.getString("code");
            if (!"0".equals(code)) {
                log.error("发送短信失败，jsonObj" + jsonObj.toJSONString());
                bizResult.setMessage("信息发送失败");
            }
        } catch (Exception e) {
            log.error("发送短信失败" + e);
            bizResult.setMessage("信息发送失败");
        }
        return bizResult;
    }

    /**
     * 获取云片短信模板
     *
     * @param tplId 模板id
     * @param type
     * @return
     */
    public static BizResult<List<SmsTplVO>> getYunPianSmsTpls(Long tplId, Integer type) {
        BizResult<List<SmsTplVO>> bizResult = new BizResult<>();
        MultivaluedMapImpl formData = new MultivaluedMapImpl();

        if (tplId != null) {
            formData.add("tpl_id", tplId);
        }
        BizResult<String> bizResultStr = null;
        try {
            bizResultStr = operatorYunPian(SmsConstant.YP_GET_SMS_TPLS, formData, type);
            String responseStr = bizResultStr.getData();
            try {
                if (tplId == null) {
                    List<SmsTplVO> list = JSON.parseArray(responseStr, SmsTplVO.class);
                    if (list != null && list.size() > 0) {
                        bizResult.setData(list);
                    }
                } else {
                    List<SmsTplVO> list = Lists.newArrayList(JSON.parseObject(responseStr, SmsTplVO.class));
                    if (list != null && list.size() > 0) {
                        bizResult.setData(list);
                    }
                }
            } catch (Exception e) {
                log.error("Parse response error. TplId is {}. Type is {}.", tplId, type, e);
                bizResult.setSuccess(false);
                bizResult.setMessage("获取模板失败" + JSON.parseObject(responseStr).get("msg"));
            }

        } catch (Exception e) {
            log.error("获取云片模板失败:" + e);
            bizResult.setSuccess(false);
            bizResult.setMessage("获取模板失败");
        }
        return bizResult;
    }

    /**
     * 添加云片短信模板
     *
     * @param tplContent
     * @param type
     * @return
     */
    public static BizResult<String> addYunPianSmsTpl(String tplContent, Integer type) {
        BizResult<String> bizResult = new BizResult<>();
        MultivaluedMapImpl formData = new MultivaluedMapImpl();

        formData.add("tpl_content", tplContent);

        try {
            bizResult = operatorYunPian(SmsConstant.YP_ADD_SMS_TPL, formData, type);
            bizResult = getResult(bizResult.getData());
        } catch (Exception e) {
            log.error("添加云片短信模板失败:" + e);
            bizResult.setSuccess(false);
        }

        return bizResult;
    }

    /**
     * 更新云片短信模板
     *
     * @param tplId
     * @param tplContent
     * @param type
     * @return
     */
    public static BizResult<String> updateYunPianSmsTpl(Long tplId, String tplContent, Integer type) {
        BizResult<String> bizResult = new BizResult<>();
        MultivaluedMapImpl formData = new MultivaluedMapImpl();

        formData.add("tpl_id", tplId);
        formData.add("tpl_content", tplContent);
        try {
            bizResult = operatorYunPian(SmsConstant.YP_UPDATE_SMS_TPL, formData, type);
            bizResult = getResult(bizResult.getData());

        } catch (Exception e) {
            log.error("更新云片模板失败:" + e);
            bizResult.setSuccess(false);
        }

        return bizResult;
    }

    /**
     * 删除云片短信模板
     *
     * @param tplId
     * @param type
     * @return
     */
    public static BizResult<String> delYunPianSmsTpl(Long tplId, Integer type) {
        BizResult<String> bizResult = new BizResult<>();
        MultivaluedMapImpl formData = new MultivaluedMapImpl();

        formData.add("tpl_id", tplId);
        try {
            bizResult = operatorYunPian(SmsConstant.YP_DEL_SMS_TPL, formData, type);
            bizResult = getResult(bizResult.getData());
        } catch (Exception e) {
            log.error("删除云片模板失败:" + e);
            bizResult.setSuccess(false);
        }

        return bizResult;
    }

    public static BizResult<String> getResult(String responseEntity) {
        BizResult<String> bizResult = new BizResult<>();
        try {
            JSONObject jsonObj = JSON.parseObject(responseEntity);
            if (null == jsonObj) {
                bizResult.setMessage("操作失败");
                return bizResult;
            }
            Integer tplId = jsonObj.getInteger("tpl_id");
            if (tplId == null) {
                bizResult.setMessage("操作失败");
                return bizResult;
            } else {
                bizResult.setData(responseEntity);
            }
        } catch (Exception e) {
            log.error("操作失败" + e);
            bizResult.setMessage("操作失败");
        }
        return bizResult;
    }

    public static BizResult<String> operatorYunPian(String operatorUrl, MultivaluedMapImpl formData,
                                                    Integer apiKeyType) {
        BizResult<String> bizResult = new BizResult<>();
        formData.add("apikey", getYunPianApiKey(apiKeyType));
        Client client = Client.create();
        String url = SmsConstant.YP_VOICE_BASE_URL + SmsConstant.YP_API_VERSION + operatorUrl;
        WebResource webResource = client.resource(url);
        ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class,
                formData);
        String responseEntity = response.getEntity(String.class);
        bizResult.setData(responseEntity);
        return bizResult;
    }
    
    public static BizResult<String> basicSmsMethod(String url, MultivaluedMapImpl formData, Integer smsType) {
        BizResult<String> result = new BizResult<>();
        try {
            if (StringUtils.isEmpty(url) || null == formData
                    || null == smsType
                    || !SmsTypeEnum.isCorrect(smsType)) {
                log.error("param error, url formData smsType error");
                result.setSuccess(false);
                result.setMessage("参数错误");
                return result;
            }
            log.info("云片接口URL ：{}", url);
            SmsTypeEnum smsTypeEnum = SmsTypeEnum.getByCode(smsType);
            formData.add(SmsConstant.YP_PARAM_API_KEY, getYunpianApiKey(smsTypeEnum));
            Client client = Client.create();
            WebResource webResource = client.resource(url);
            ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED)
                    .post(ClientResponse.class, formData);
            String responseEntity = response.getEntity(String.class);
            result.setData(responseEntity);
            result.setSuccess(true);
        } catch(Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("调用云片接口系统异常");
        }
        return result;
    }

    public static String getYunPianApiKey(Integer type) {
        if (SmsConstant.API_KEY.intValue() == type.intValue()) {
            return SmsConstant.YP_SMS_API_KEY;
        } else if (SmsConstant.SEM_API_KEY.intValue() == type.intValue()) {
            return SmsConstant.YP_SMS_SEM_API_KEY;
        } else if (SmsConstant.DAILY_API_KEY.intValue() == type.intValue()) {
            return SmsConstant.DAILY_YP_SMS_API_KEY;
        } else {
            return null;
        }
    }
    
    public static String getYunpianApiKey(SmsTypeEnum smsTypeEnum) {
        String key;
        switch (smsTypeEnum) {
            case DAILY:
                key = SmsConstant.DAILY_YP_SMS_API_KEY;
                break;
            case SYSTEM:
                key = SmsConstant.YP_SMS_API_KEY;
                break;
            case MARKETING:
                key = SmsConstant.YP_SMS_SEM_API_KEY;
                break;
            default:
                key = null;
                break;
        }
        return key;
    }

}
